/*
 * @Author: Penk
 * @LastEditors: Penk
 * @LastEditTime: 2022-04-24 09:03:59
 * @FilePath: \puppeteer-demo\scripts\log.js
 */
// 活动管理方法
import fs from 'fs';
import path from 'path';
import moment from 'moment';

// 保存 data txt数据
var saveLog = async function (fileName, msg) {
  let ret = "";
  try {
    ret = await writeLog(fileName, msg);
  } catch (e) {
    console.log(" ==== e === ", e);
  }
};

export default {
  saveLog
};

// 写日志
async function writeLog(fileName, msg) {
  var curPath = path.resolve().split("scripts");
  var fileUrl = path.join(curPath[0], "/log/", fileName + ".txt");
  await createFolder(path.join(curPath[0], "/log"));

  var text = moment().format('yyyy-MM-DD hh:mm:ss') + "=> " + msg + "\n";

  try {
    // 同步地将数据追加到文件中，如果文件尚不存在则创建该文件。
    fs.appendFileSync(fileUrl, text);
    return "writeLog success!";
  } catch (err) {
    return "writeLog:" + err;
  }
}

async function createFolder(folder) {
  try {
    fs.accessSync(folder);
  } catch (e) {
    fs.mkdirSync(folder);
  }
}